import gui.SWTCodegGUI;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.graphics.RGB;

import codeg.Codeg;


public class ColorCodegGUI implements SWTCodegGUI {
    private Composite color_area;
    private ColorCodeg codeg;

    public void populate(Composite content) {
        content.setLayout(new GridLayout(2, false));
        final Display display = content.getDisplay();

        Label label = new Label(content, SWT.LEFT);
        label.setText("Current color: ");

        final Composite color = new Composite(content, SWT.NONE);
        color.setLayoutData(new GridData(48, 16));

        Button button = new Button(content, SWT.PUSH);
        button.setText("Edit");
        button.setLayoutData(new GridData(SWT.RIGHT, SWT.BOTTOM, true, false,
            2, 1));
        button.addMouseListener(new MouseListener() {
            public void mouseDoubleClick(MouseEvent e) {};

            public void mouseUp(MouseEvent e) {
                edit();
            }

            public void mouseDown(MouseEvent e) {};

        });
        color.addPaintListener(new PaintListener() {
            public void paintControl(PaintEvent event) {
                redraw_color(display, event);
            }
        });
        color_area = color;
    }

    private RGB getRGB() {
        ColorCodeg.Color color = codeg.getColor();
        return new RGB(color.red, color.green, color.blue);
    }

    private void redraw_color(Display display, PaintEvent event) {
        event.gc.setBackground(new Color(display, getRGB()));
        event.gc.fillRectangle(0, 0, 48, 16);
    }

    private void edit() {
        ColorDialog dialog = new ColorDialog(color_area.getShell());
        dialog.setRGB(getRGB());
        RGB rgb = dialog.open();
        if (rgb != null) {
            ColorCodeg.Color color = codeg.getColor();
            color.red = rgb.red;
            color.green = rgb.green;
            color.blue = rgb.blue;
            color_area.redraw();
            color_area.update();
            codeg.changed();
        }
    }

    public Codeg getCodeg() {
        return this.codeg;
    }

    public void setCodeg(Codeg codeg) {
        this.codeg = (ColorCodeg) codeg;
    }
}
